<?php

namespace app\wenchuang\controller;

use cmf\controller\AdminBaseController;
// 引入鉴权类
use Qiniu\Auth;
// 引入上传类
use Qiniu\Storage\UploadManager;

require CMF_ROOT.'vendor/qiniu/autoload.php';
class IndexController extends AdminBaseController
{
    private $accessKey = "47EqIiy3lYBoOJatLB2zrsqhUuEqaJxIKaWXJkfg";
    private $secretKey = "KPMO60-KzC8uKJiO6-vINBPPwIFhTpIOka9yf3Qe";
    private $bucket = "liupengyang";

    public function index()
    {
        if ($this->request->isPost()){
            $file = $this->request->file('image');
            if(!$file){
                $this->error('请选择图片');
            }
            //图片后缀名
            $ext = $file->getOriginalExtension();
            // 构建鉴权对象
            $auth = new Auth($this->accessKey, $this->secretKey);
            // 生成上传 Token
            $token = $auth->uploadToken($this->bucket);
            // 要上传文件的本地路径
            $filePath = $file->getPathname();
            // 上传到存储后保存的文件名
            $key = uniqid().time().'.'.$ext;
            // 初始化 UploadManager 对象并进行文件的上传。
            $uploadMgr = new UploadManager();
            // 调用 UploadManager 的 putFile 方法进行文件的上传。
            list($ret, $err) = $uploadMgr->putFile($token,$key,$filePath);
            if ($err !== null) {
                $this->error($err);
            } else {
                $this->success('上传成功');
            }
        }
        return $this->fetch('index');
    }
}